﻿using Bomber.TF.Common.GDI;
using Bomber.TF.View.ViewEx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bomber.TF.GameCenter
{
    public class ImageObject : IDisposable
    {
        public ImageObject(string path) : this(new Bitmap(path))
        {
        }
        public ImageObject(Bitmap bitmap)
        {
            SetBitmap(bitmap);

        }
        private void SetBitmap(Bitmap bit)
        {
            Width = bit.Width;
            Height = bit.Height;
            BitmapPtr = bit.GetHbitmap();
            bit.Dispose();
        }
        public int Width { get; private set; }
        public int Height { get; private set; }
        public IntPtr BitmapPtr { get; private set; }

        #region 垃圾释放
        private bool _disposed;
        private object _obj = new object();
        public void Dispose()
        {
            Dispose(true);
            // 请求公共语言运行时不要调用该对象上的终结器（在C#中就是指不要调用析构函数）
            GC.SuppressFinalize(this);
        }
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);
        protected virtual void Dispose(bool disposing)
        {
            // 保证线程安全
            lock (_obj)
            {
                if (!_disposed)
                {
                    if (disposing)
                    {
                        // Release managed resources
                    }

                    // Release unmanaged resources
                    if (BitmapPtr != IntPtr.Zero)
                    {
                        GDI32.DeleteObject(BitmapPtr);
                        BitmapPtr = IntPtr.Zero;
                    }
                    _disposed = true;
                }
            }
        }
        public void Close()
        {
            Dispose();
        }
        ~ImageObject()
        {
            Dispose(false);
        }
        #endregion
    }
}
